package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.*;
import com.app.domain.response.ExternalResponse;
import com.app.domain.response.GenericResponse;
import com.app.domain.response.ResponseResult;
import com.app.domain.yj.YjjlInfo;
import com.app.domain.zl.ZljlData;
import com.app.domain.zl.ZljlInfo;
import com.app.service.UploadService;
import com.app.service.YjService;
import com.app.service.ZlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/public")
public class PublicController {
    @Autowired
    ZlService zlService;
    @Autowired
    YjService yjService;
    @Autowired
    UploadService uploadService;
    @Value("${zl.addZhanglaHost}")
    private String addZhanglaHost;
    @Value("${zl.zhanglaSAddListHost}")
    private String zhanglaSAddListHost;
    @Value("${zl.zhanglaSSAddListHost}")
    private String zhanglaSSAddListHost;
    @Value("${zl.editService}")
    private String editService;

    @Value("${zl.shebeibianhao}")
    private String shebeibianhao;
    @Value("${zl.rwdService}")
    private String rwdService;

    @RequestMapping(value = {"/list"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}, produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String list(@RequestBody Map<String, String> requestData) {
        System.out.println("字符集" + System.getProperty("file.encoding"));
        String searchBusiType = (String) requestData.get("searchBusiType");
        int curPage = Integer.valueOf((String) requestData.get("curPage")).intValue();
        int pageSize = Integer.valueOf((String) requestData.get("pageSize")).intValue();
        int currentPage = (curPage - 1) * pageSize;
        String responseContent = "";
        Map<String, Object> parameterMap = new HashMap();
        parameterMap.put("pageSize", Integer.valueOf(pageSize));
        parameterMap.put("currentPage", Integer.valueOf(currentPage));
        parameterMap.put("searchIsAll", requestData.get("searchIsAll"));

        Map<String, String> responseExpend = new HashMap();
        if ("0".equals(searchBusiType)) {
            List<ZljlInfo> resultDatas = zlService.queryZljlInfoPage(requestData.get("searchIsAll"));

            responseContent = JSON.toJSONString(resultDatas);
        }
        if ("1".equals(searchBusiType)) {
            List<YjjlInfo> resultDatas = yjService.queryYjlInfoPage(requestData.get("searchIsAll"));
            responseContent = JSON.toJSONString(resultDatas);
        }
        ExternalResponse externalResponse = new ExternalResponse(0, responseContent, JSON.toJSONString(responseExpend));
        return JSON.toJSONString(externalResponse);
    }

    @RequestMapping(value = {"/getRwdlist"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}, produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String getRwdlist() {
        Map<String, String> resultMap;
        try {
            resultMap = uploadService.getRwdlist(rwdService, shebeibianhao);
            if (resultMap == null) {
                resultMap = new HashMap<>();
            }
        } catch (Exception e) {
            // 记录异常日志，返回错误响应
            log.error("获取任务单列表失败", e);
            ExternalResponse externalResponse = new ExternalResponse(-1, "{}", "获取任务单列表失败: " + e.getMessage());
            return JSON.toJSONString(externalResponse);
        }

        ExternalResponse externalResponse = new ExternalResponse(0, JSON.toJSONString(resultMap), "");
        return JSON.toJSONString(externalResponse);
    }


    @RequestMapping(value = {"/uploadData"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}, produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String uploadData(@RequestBody Map<String, Object> requestData) {
        ExternalResponse externalResponse = null;
        String searchBusiType = (String) requestData.get("searchBusiType");
        String[] idsArray = ((String) requestData.get("ids")).split(",");
        String bridge = (String) requestData.get("bridge");
        // 获取张拉任务单数据
        Map<String, Object> rwdData = (Map<String, Object>) requestData.get("rwdData");
        if (rwdData != null) {
            log.info("收到张拉任务单数据: " + JSON.toJSONString(rwdData));
        }
        int total = idsArray.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuilder responseContent = new StringBuilder();
        responseContent.append("本次共上传数据：【").append(total).append("】条,");
        if ("0".equals(searchBusiType)) {
            for (String id : idsArray) {
                try {
                    int recordId;
                    try {
                        recordId = Integer.parseInt(id);
                    } catch (NumberFormatException e) {
                        log.error("无效的ID格式: " + id, e);
                        failTotal++;
                        continue;
                    }

                    ZljlInfo zljlInfo = zlService.queryZljlInfoById(recordId);
                    List<ZljlData> zljlDataList = zlService.findZljlDataByQlbh(zljlInfo.getQlbh());
                 /*   Map<String, ZljlData> map = zljlDataList.stream()
                            .filter(data -> data.getGsbh().contains("左N4"))
                            .collect(HashMap::new, (m, data) -> {
                                if (data.getGsbh().contains("1")) {
                                    m.put("ZN4100", data);
                                } else {
                                    m.put("ZN450", data);
                                }
                            }, HashMap::putAll);*/
                    List<String> qlbhList = zljlDataList.stream()
                            .map(ZljlData::getGsbh)
                            .collect(Collectors.toList());
                    Map<String, Object> selectedRwdData = (Map<String, Object>) rwdData.get(id);
                    String selectedRwd = selectedRwdData != null ? (String) selectedRwdData.get("value") : null;
                    String selectedText = selectedRwdData != null ? (String) selectedRwdData.get("selectedText") : null;

                    TensionProjectInfo tensionProjectInfo = uploadService.getTensionProjectInfo(zljlInfo, zljlDataList, bridge, shebeibianhao, selectedRwd, selectedText);
                    if (tensionProjectInfo == null) {
                        updateZljlInfo(recordId, "0");
                        failTotal++;
                        continue;
                    }
                    Map<String, String> requestMap = new HashMap<>();
                    requestMap.put("uuid", selectedRwd);
                    requestMap.put("status", "1");
                    requestMap.put("status2", "0");
                    requestMap.put("wcstatus", "1");

                    Map<String, Object> maps = uploadService.getTensionMainData(zljlInfo, zljlDataList, tensionProjectInfo.getSyjid(), shebeibianhao, selectedRwd, selectedText, qlbhList);
                    List<TensionMainData> tensionMainDataList = (List<TensionMainData>) maps.get("tensionMainDataList");
                    List<TensionSubData> tensionSubDataList = (List<TensionSubData>) maps.get("tensionSubDataList");
                    List<TensionCurveData> tensionCurveDataList = (List<TensionCurveData>) maps.get("tensionCurveDataList");

                    tensionProjectInfo.setZhanglam(tensionMainDataList);
         /*           String jsonString = JSON.toJSONString(tensionProjectInfo);
                    String jsonString1 = JSON.toJSONString(tensionSubDataList);
                    String jsonString2 = JSON.toJSONString(tensionCurveDataList);
                    System.out.println(jsonString);
                    System.out.println(jsonString1);
                    System.out.println(jsonString2);*/

                    GenericResponse pResult = uploadService.sendMessage(addZhanglaHost, JSON.toJSONString(tensionProjectInfo));
                    if (isSuccess(pResult)) {
                        MainTrZhanglaS mainTrZhanglaS = new MainTrZhanglaS();
                        mainTrZhanglaS.setTrZhanglaS(tensionSubDataList);
                        GenericResponse sResult = uploadService.sendMessage(zhanglaSAddListHost, JSON.toJSONString(mainTrZhanglaS));
                        if (isSuccess(sResult)) {
                            // 按30条一份切割tensionCurveDataList并分批上传
                            int totalCurveData = tensionCurveDataList.size();
                            int batchSize = 30;
                            boolean curveUploadSuccess = true;
                            for (int i = 0; i < totalCurveData; i += batchSize) {
                                int endIndex = Math.min(i + batchSize, totalCurveData);
                                List<TensionCurveData> batch = tensionCurveDataList.subList(i, endIndex);
                                MainTrZhanglaSS mainTrZhanglaSS = new MainTrZhanglaSS();
                                mainTrZhanglaSS.setTrZhanglaSS(batch);
                                GenericResponse cResult = uploadService.sendMessage(zhanglaSSAddListHost, JSON.toJSONString(mainTrZhanglaSS));
                                if (!isSuccess(cResult)) {
                                    curveUploadSuccess = false;
                                    break;
                                }
                            }
                            GenericResponse mResult = uploadService.putMessage(editService, JSON.toJSONString(requestMap));
                            if (curveUploadSuccess && isSuccess(mResult)) {
                                updateZljlInfo(recordId, "1");
                                succTotal++;
                            } else {
                                updateZljlInfo(recordId, "0");
                                failTotal++;
                            }
                        } else {
                            updateZljlInfo(recordId, "0");
                            failTotal++;
                        }
                    } else {
                        updateZljlInfo(recordId, "0");
                        failTotal++;
                    }
                } catch (Exception e) {
                    updateZljlInfo(Integer.parseInt(id), "0");
                    failTotal++;
                    log.error("上传数据失败，ID: " + id, e);
                }
            }
        }
        responseContent.append("成功【").append(succTotal).append("】条,失败").append(failTotal).append("条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return JSON.toJSONString(externalResponse);
    }
    
    /**
     * 实时上传单个孔数据
     * @param requestData 请求数据
     * @return 上传结果
     */
    @RequestMapping(value = {"/uploadSingleHole"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}, produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String uploadSingleHole(@RequestBody Map<String, Object> requestData) {
        try {
            int zljlInfoId = Integer.parseInt((String) requestData.get("zljlInfoId"));
            String gsbh = (String) requestData.get("gsbh");
            String bridge = (String) requestData.get("bridge");
            Map<String, Object> rwdData = (Map<String, Object>) requestData.get("rwdData");
            
            // 查询主表信息
            ZljlInfo zljlInfo = zlService.queryZljlInfoById(zljlInfoId);
            if (zljlInfo == null) {
                return JSON.toJSONString(new ExternalResponse(-1, "未找到张拉记录", ""));
            }
            
            // 查询孔数据
            List<ZljlData> zljlDataList = zlService.findZljlDataByQlbh(zljlInfo.getQlbh());
            ZljlData targetZljlData = null;
            for (ZljlData data : zljlDataList) {
                if (gsbh.equals(data.getGsbh())) {
                    targetZljlData = data;
                    break;
                }
            }
            
            if (targetZljlData == null) {
                return JSON.toJSONString(new ExternalResponse(-1, "未找到指定孔数据", ""));
            }
            
            // 获取任务单数据
            String rwdValue = null;
            String rwdText = null;
      /*      if (rwdData != null) {
                Map<String, Object> selectedRwdData = (Map<String, Object>) rwdData.get(String.valueOf(zljlInfoId));
                rwdValue = selectedRwdData != null ? (String) selectedRwdData.get("value") : null;
                rwdText = selectedRwdData != null ? (String) selectedRwdData.get("selectedText") : null;
            }
            
            // 上传单个孔数据
            boolean success = zlService.uploadSingleHoleData(zljlInfo, targetZljlData, shebeibianhao, rwdValue, rwdText);
            
            if (success) {
                return JSON.toJSONString(new ExternalResponse(0, "上传成功", ""));
            } else {
                return JSON.toJSONString(new ExternalResponse(-1, "上传失败", ""));
            }*/
            return JSON.toJSONString(new ExternalResponse(0, "上传成功", ""));
        } catch (Exception e) {
            log.error("上传单个孔数据失败", e);
            return JSON.toJSONString(new ExternalResponse(-1, "上传异常: " + e.getMessage(), ""));
        }
    }

    private boolean isSuccess(GenericResponse result) {
        return result.getSuccess();
    }

    private void updateYjjlInfo(int id, String status) {
        yjService.updateYjjlInfo(status, id);
    }

    private void updateZljlInfo(int id, String status) {
        zlService.updateUploadedById(status, id);
    }

}